package org.mspring.mlog.security.login;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功后跳转方法
 *
 * @author Gao Youbo
 * @since 2013-1-14
 */
public class LoginSuccesssHandler extends SimpleUrlAuthenticationSuccessHandler {

    private static final Logger log = LoggerFactory.getLogger(LoginFailureHandler.class);

    private RequestCache requestCache = new HttpSessionRequestCache();

    public void setRequestCache(RequestCache requestCache) {
        this.requestCache = requestCache;
    }

    public LoginSuccesssHandler() {
        super.setAlwaysUseDefaultTargetUrl(false);
        super.setUseReferer(true);
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        //SavedRequest savedRequest = requestCache.getRequest(request, response);
        //
        //if (savedRequest == null) {
        //    sendDefaultTargetUrl(request, response, authentication);
        //    return;
        //}
        //String targetUrlParameter = getTargetUrlParameter();
        //if (isAlwaysUseDefaultTargetUrl() || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
        //    requestCache.removeRequest(request, response);
        //    super.onAuthenticationSuccess(request, response, authentication);
        //    return;
        //}
        //clearAuthenticationAttributes(request);
        //String targetUrl = savedRequest.getRedirectUrl();
        //log.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
        //getRedirectStrategy().sendRedirect(request, response, targetUrl);
        response.sendRedirect(getDefaultTargetUrl());
    }

    /**
     * 跳转到DefaultURL
     *
     * @throws ServletException
     * @throws IOException
     */
    public void sendDefaultTargetUrl(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        handle(request, response, authentication);
        clearAuthenticationAttributes(request);
    }
}
